package com.shunhao.network.interceptor;

import android.text.TextUtils;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.shunhao.network.NetConstant;
import com.shunhao.network.RetrofitHelper;
import com.shunhao.network.exception.ApiException;
import com.shunhao.network.model.NeedLoginEvent;
import com.shunhao.network.rxjava.BaseObserver;
import com.shunhao.network.rxjava.RxManager;
import com.shunhao.utils.LogUtil;
import com.shunhao.utils.PreUtils;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;


/**
 * <pre>
 * 文件名：	InterceptorUtil
 * 作　者：	gykang
 * 时　间：	2018/7/19 10:47
 * 描　述：  Retrofit2 拦截器工具类
 * @author kang gui yang
 * </pre>
 */
public class InterceptorUtil {

    private static final String TAG = InterceptorUtil.class.getSimpleName();
    private static String token;
    private static String registerId = "";

    /**
     * 日志拦截器
     *
     * @return 返回日志拦截器
     */
    public static HttpLoggingInterceptor logInterceptor() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(message -> {
            try {
                LogUtil.e(TAG, message);
            } catch (Exception e) {
                LogUtil.e(TAG, "[拦截异常了] : " + message);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        return loggingInterceptor;
    }

    /**
     * BaseUrl拦截器
     */
    public static class HostInterceptor implements Interceptor {

        @NotNull
        @Override
        public Response intercept(Chain chain) throws IOException {
            //重新赋值
            HttpUrl newHost = HttpUrl.parse(NetConstant.BASE_URL);
            LogUtil.e(TAG, "------------------------------Host拦截器------------------------------");
            LogUtil.e(TAG, "[ROOT_URL] : " + newHost);
            Request request = chain.request();
            Request.Builder builder = request.newBuilder();

            HttpUrl oldHttpUrl = request.url();
            //重建新的HttpUrl，修改需要修改的url部分
            HttpUrl newFullUrl = oldHttpUrl
                    .newBuilder()
                    .scheme(newHost.scheme())
                    .host(newHost.host())
                    .port(newHost.port())
                    .build();
            LogUtil.e(TAG, "[拦截转url] : " + newFullUrl.url().toString());
            return chain.proceed(builder.url(newFullUrl).build());
        }
    }


    /**
     * Header拦截器 token拦截器
     * 第一次进去默认 token Basic dXBiZXN0OnVwYmVzdA== (有空格)
     *
     * @return
     */
    public static Interceptor headerInterceptor() {
        return chain -> {
            //在这里你可以做一些想做的事,比如token失效时,重新获取token
            //--------------------直接401 if 401-----------------------------------------------------
            token = SPUtils.getInstance().getString("ACCESS_TOKEN_KEY");
            if (registerId.isEmpty()) {
                registerId = SPUtils.getInstance().getString(PreUtils.REGISTER_ID);
            }
            if (TextUtils.isEmpty(token)) {
                String apiVersion = chain.request().header("Api-Version");

                Request mRequest = chain.request()
                        .newBuilder()
                        .header("Api-Version", ObjectUtils.isEmpty(apiVersion) ? "1.0" : apiVersion)
                        .addHeader("User-Client", "mobileApp")
                        .build();
                Response response = chain.proceed(mRequest);
                LogUtil.d(TAG, "[无 token TextUtils.isEmpty(token) isTokenExpired] = " + response.code());
                if (response.code() == ApiException.NO_AUTH_FRAME) {
                    EventBus.getDefault().post(new NeedLoginEvent());
                }
                return response;
            }
            //--------------------获取新的token if 401-----------------------------------------------------
            String apiVersion = chain.request().header("Api-Version");

            Request mRequest =
                    chain.request()
                            .newBuilder()
                            .header("Api-Version", ObjectUtils.isEmpty(apiVersion) ? "1.0" : apiVersion)
                            .addHeader("User-Client", "mobileApp")
                            .addHeader("Authorization", token)
                            .addHeader("deviceNumber", registerId)
                            .build();
            LogUtil.d(TAG, "[拦截器中获取到的token] : " + token);
            LogUtil.d(TAG, "[拦截器中获取到的registerId] : " + registerId);
            Response response = chain.proceed(mRequest);

            // 判断是否是4.1
            if (isTokenExpired(response)) {
                token = "";
                EventBus.getDefault().post(new NeedLoginEvent());
            }

            return response;
        };

    }

    /**
     * 根据Response判断Token是否失效
     * 401 表示已过期
     *
     * @param response response
     * @return
     */
    private static boolean isTokenExpired(Response response) {
        LogUtil.d(TAG, "[isTokenExpired] = " + response.code());
        if (response.code() == ApiException.NO_AUTH_FRAME) {
            return true;
        }
        return false;

    }

    /**
     * 获取新的token
     *
     * @return
     */
    private static String getNewToken() {
        HashMap hashMap = new HashMap<String, Object>(1);
        String tokenInner = SPUtils.getInstance().getString("ACCESS_TOKEN_KEY");
        hashMap.put("token", tokenInner);
        LogUtil.d(TAG, "[get new Token = ] " + tokenInner);
      /*  RxManager.getInstance().doSubscribe(RetrofitHelper.INSTANCE.getMApiService()
                .refreshToken(getRequestBody2Json(hashMap)), new BaseObserver<String>() {
            @Override
            protected void onSuccess(@Nullable String s) {
                if (!TextUtils.isEmpty(s)) {
                    token = s;
                    SPUtils.getInstance().put("ACCESS_TOKEN_KEY", token);
                    LogUtil.d(TAG, "[已重新保存token]");
                }
            }

            @Override
            protected void onError(@Nullable String message) {

            }
        });*/

        LogUtil.d(TAG, "[刷新获取新的token返回] ： " + token);
        return token;
    }

    public static RequestBody getRequestBody2Json(HashMap<String, Object> commitHashMap) {
        String json = GsonUtils.toJson(commitHashMap);
        return RequestBody.create(MediaType.parse("application/json"), json);
    }

    /**
     * 缓存拦截器
     *
     * @return
     */
  /*  public static Interceptor getCacheInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                //CONTEXT不能为空
                if (!NetworkUtils.isConnected(PalApplication.getInstance().getApplicationContext())) {
                    int maxStale = 4 * 7 * 24 * 60; // 离线时缓存保存4周,单位:秒
                    CacheControl tempCacheControl = new CacheControl.Builder()
                            .onlyIfCached()
                            .maxStale(maxStale, TimeUnit.SECONDS)
                            .build();
                    request = request.newBuilder()
                            .cacheControl(tempCacheControl)
                            .build();
                }
                return chain.proceed(request);
            }
        };
    }*/


}
